package com.xuchaotong.order.controller;

import com.xuchaotong.order.entity.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 311633
 * @version 1.0
 * @ClassName:
 * @Description:
 * @date 2017/11/28 9:34
 */
@RestController
public class HelloController {

    final Map<Integer, DeferredResult> resultMap = new ConcurrentHashMap();

    @RequestMapping("/hello")
    public String index() {
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Hello world!";
    }

    @GetMapping("/long-polling")
    public DeferredResult<Order> longPolling() {
        DeferredResult deferredResult = new DeferredResult(0l);
        resultMap.put(deferredResult.hashCode(), deferredResult);

        deferredResult.onCompletion(() -> {
//            resultMap.remove(deferredResult.hashCode());
//            String result = String.valueOf(deferredResult.getResult());
            System.err.println("剩余：" + resultMap.size() + "个deferredResult未响应。");
        });
        return deferredResult;
    }

    @GetMapping("/return/long-polling")
    public void returnLongPollingVal() {
        Order order;
        for (Map.Entry<Integer,DeferredResult> entry : resultMap.entrySet()) {
            order = new Order();
            order.setOrderNo("09877773773");
            entry.getValue().setResult(order);
        }
    }
}
